package com.module.overview.ui.schedule.provider

import android.util.Log
import android.view.View
import android.widget.TextView
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.core.RouterHub
import com.common.app.data.bean.KeyBundle
import com.common.app.data.bean.overView.CardSettingModel
import com.common.app.helper.RouterHelper
import com.common.app.utls.TimeUtils
import com.common.app.utls.TimeUtils.getTimeDateLong
import com.common.app.widget.SegmentProgressBar
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.setSafeOnClickListener
import com.common.base.app.extras.setVisible
import com.common.base.utils.ViewUtils
import com.module.ble.data.bean.CusChartData
import com.module.ble.repo.HeartRateRepo
import com.module.ble.repo.UserStressRepo
import com.module.ble.utils.AllCardTypeConfig
import com.module.overview.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import java.util.Calendar

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/6/16
 *
 * 描述：压力卡片
 *
 * 修订历史：完成度90%
 *
 */
class OvMainPressureCardProvider(
    override val itemViewType: Int = AllCardTypeConfig.TYPE_CARD_PRESSURE,
    override val layoutId: Int = R.layout.overview_main_pressure_crad_provider
) : BaseItemProvider<CardSettingModel>() {

    var tvPressureStatus: TextView? = null
    var tvPressureTime: TextView? = null
    var tvPressureSuggestion: TextView? = null
    var segmentProgressBar:SegmentProgressBar? = null

    init {
    }

    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
        tvPressureStatus = viewHolder.getView(R.id.tvPressureStatus)
        tvPressureTime = viewHolder.getView(R.id.tvPressureTime)
        tvPressureSuggestion = viewHolder.getView(R.id.tvPressureSuggestion)

        segmentProgressBar = viewHolder.getView<SegmentProgressBar>(R.id.segmentProgressBar).apply {
            // 设置4段，比例分别为 30%, 20%, 25%, 25%
            setSegmentRatios(floatArrayOf(0.3f, 0.3f, 0.2f, 0.2f))
//            setProgress(1)
        }
        super.onViewHolderCreated(viewHolder, viewType)
    }

    override fun onViewDetachedFromWindow(holder: BaseViewHolder) {
        super.onViewDetachedFromWindow(holder)
    }

    override fun convert(helper: BaseViewHolder, item: CardSettingModel) {
        helper.itemView.setVisible(item.isEnabled)
        helper.getView<View>(R.id.totalPressureCard).setSafeOnClickListener {
            RouterHelper.navigationPostcard(RouterHub.ROUTER_OVERVIEW_CARD_HISTORY_DETAILS)
                .withString(KeyBundle.BUNDLE_TITLE, item.name)
                .navigation()
        }
        getTheDayStress()
    }

    /**
     * 获取当天压力
     */
    private fun getTheDayStress(){
        doOnIOThread {
            //当天压力
            UserStressRepo.instance.findLatestByDay(getTimeDateLong())?.let { originalIt->

                val stressValueStr = when(originalIt.stress.toInt()){
                    in 0..30 -> ViewUtils.getString(R.string.common_pressure_relax_hint)
                    in 31..60 -> ViewUtils.getString(R.string.common_pressure_normal_hint)
                    in 61..80 -> ViewUtils.getString(R.string.common_pressure_medium_hint)
                    in 81..100 -> ViewUtils.getString(R.string.common_pressure_high_hint)
                    else -> ViewUtils.getString(R.string.common_rail_unit) // 处理超出范围的情况
                }

                // 创建48个时间区间块的CusChartData数组
                val result = mutableListOf<CusChartData>()

                // 获取curTime当天的0点时间戳
                val calendar = Calendar.getInstance()
                calendar.timeInMillis = getTimeDateLong()
                calendar.set(Calendar.HOUR_OF_DAY, 0)
                calendar.set(Calendar.MINUTE, 0)
                calendar.set(Calendar.SECOND, 0)
                calendar.set(Calendar.MILLISECOND, 0)
                val startOfDay = calendar.timeInMillis

                for (index in 0 until 48) {
                    val timeOffset = index * 30 * 60 * 1000L // 每30分钟的时间偏移
                    val intervalStartTime = startOfDay + timeOffset
                    val intervalEndTime = startOfDay + timeOffset + (30 * 60 * 1000L) // 加30分钟作为结束时间

                    result.add(
                        CusChartData(
                            createdTime = intervalStartTime,
                            endTime = intervalEndTime,
                            mValue = 0f,
                            minValue = 0f,
                            dayNum = 0
                        )
                    )
                }

                //当前时间区间
                val curIntervalBean = result.find { cusChartData ->
                    val currentTime = getTimeDateLong()
                    currentTime >= cusChartData.createdTime && currentTime < cusChartData.endTime
                }

                // 切换到主线程更新UI
                doOnUiThread {
                    tvPressureStatus?.text = stressValueStr
                    segmentProgressBar?.setProgress(originalIt.stress.toInt())
                    curIntervalBean?.let { curIntervalBeanIt->
                        tvPressureTime?.text = "${TimeUtils.getHourMinute(curIntervalBeanIt.createdTime)}-${TimeUtils.getHourMinute(curIntervalBeanIt.endTime)}"
                    }
                }
            }
        }
//        // 使用Flow观察数据变化
//        UserStressRepo.instance.findByTimestampTheDayFlow(getTimeDateLong())
//            .flowOn(Dispatchers.IO) // 在IO线程执行数据库操作
//            .onEach { originalListIt ->
//                if (originalListIt.isNullOrEmpty()) return@onEach
//                val theDayAverage = if (originalListIt.isNotEmpty()) { // 当日平均
//                    originalListIt.map { it.stress }.average().toInt()
//                } else {
//                    0
//                }
//
//
//                val stressValueStr = when(theDayAverage){
//                    in 0..30 -> ViewUtils.getString(R.string.common_pressure_relax_hint)
//                    in 31..60 -> ViewUtils.getString(R.string.common_pressure_normal_hint)
//                    in 61..80 -> ViewUtils.getString(R.string.common_pressure_medium_hint)
//                    in 81..100 -> ViewUtils.getString(R.string.common_pressure_high_hint)
//                    else -> ViewUtils.getString(R.string.common_rail_unit) // 处理超出范围的情况
//                }
//                // 切换到主线程更新UI
//                doOnUiThread {
//                    tvPressureStatus?.text = stressValueStr
//                    segmentProgressBar?.setProgress(theDayAverage)
//                }
//            }
//            .catch { exception ->
//                // 处理异常情况
//                Log.e("OvMainPressureCardProvider", "获取当天压力数据失败", exception)
//            }
//            .launchIn(GlobalScope) // 在生命周期范围内启动Flow
    }
}